import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { message } from 'ant-design-vue'
import Modal from 'ant-design-vue/es/modal'
Vue.use(message)
message.config({
  top: `400px`,
  duration: 4
})
// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL + '/api', // api base_url
  timeout: 20000 // 请求超时时间
})

const err = error => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      // notification.error({
      //   message: '认证信息过期',
      //   description: 'Authorization verification failed'
      // })
      store.dispatch('Logout').then(() => {
        let secondsToGo = 5
        const modal = Modal.warning({
          centered: true,
          title: '警告',
          content: `登陆数据已过期 ${secondsToGo} 秒后返回登陆页!`,
          onOk() {
            if (token) {
              window.location.reload()
            }
          }
        })
        const interval = setInterval(() => {
          secondsToGo -= 1
          modal.update({
            content: `登陆数据已过期 ${secondsToGo} 秒后返回登陆页!`
          })
        }, 1000)
        setTimeout(() => {
          clearInterval(interval)
          modal.destroy()
          if (token) {
            window.location.reload()
          }
        }, secondsToGo * 1000)
        // setTimeout(() => {
        //   window.location.reload()
        // }, 1500)
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use(response => {
  if (response.data === '请求未授权，拒绝访问。') {
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
  }
  //20200711
  const res = response.data
  if (res.success == undefined) {
    return res
  } else {
    if (res.code == 10000) {
      // message.success(res.message)
      return res
    } else {
      message.error(`${res.message}`)
    }
  }
}, err)

service.defaults.retry = 4
service.defaults.retryDelay = 1000
service.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
  var config = err.config
  // 如果config不存在或未设置重试选项，请拒绝
  if (!config || !config.retry) return Promise.reject(err)
  // 设置变量跟踪重试次数
  config.__retryCount = config.__retryCount || 0
  // 检查是否已经达到最大重试总次数
  if (config.__retryCount >= config.retry) {
    // 抛出错误信息
    return Promise.reject(err)
  }
  // 增加请求重试次数
  config.__retryCount += 1
  // 创建新的异步请求
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve()
    }, config.retryDelay || 1)
  })
  // 返回axios信息，重新请求
  return backoff.then(function() {
    return axios(config)
  })
})

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export { installer as VueAxios, service as axios }
